package tt.dz.biz.dao.channel;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import tt.dz.common.DateUtil;
import tt.dz.common.LogUtil;
import tt.dz.common.PayChannelAccountCheckEnum;
import tt.dz.vo.AlipayBillRecordVO;
import tt.dz.vo.ChannelCheckdetailVO;

@Repository("aLiPayChannelCheckDao")
public class ALiPayChannelCheckDaoImp
  extends ChannelCheckDaoImp
{
  private static final String CHANNEL_NO = PayChannelAccountCheckEnum.ALIPAY.channelCode();
  private static final String COMPARE_SQL = "SELECT a.channel_code,a.accounting_date as tran_accounting_date,a.trade_no,a.plat_time,a.payment_amount,  a.pay_state_code,a.pay_type_code,b.amount as thd_amount,b.refund_amount,b.trade_state,b.tran_no as thd_tran_no from ms_tran_info a LEFT JOIN  alipay_bill_record b on    a.order_no=b.merchant_order  where a.channel_code=:channelCode and  (a.check_account_sate is null or a.check_account_sate='00')   ";
  private static final String UPDATE_ALIPAY_BILL_RECORD = "update alipay_bill_record set isCheck=1 where  tran_no=:tranNo ";
  private static final String INSERT_ALIPAY_BILL_RECORD = "insert into alipay_bill_record(tran_no,merchant_order,trade_create_time,pay_time,recent_update_time,trade_origin,type,trade_opposite,goods_name,amount,income_expenditure,trade_state,service_charge,refund_amount,remark,ischeck,import_time)  values(:tranNo,:merchantOrder,:tradeCreateTime,:payTime,:recentUpdateTime,:tradeOrigin,:type,:tradeOpposite,:goodsName,:amount,:incomeExpenditure,:tradeState,:serviceCharge,:refundAmount,:remark,:ischeck,CURRENT_TIMESTAMP ) ";
  private static final String QUERY_ALIPAY_BILL_RECORD = "select  tran_no,merchant_order,trade_create_time,pay_time,recent_update_time,trade_origin,type,trade_opposite,goods_name,amount,income_expenditure,trade_state,service_charge,refund_amount,remark,ischeck,import_time  from alipay_bill_record where 1=1  ";
  
  public List<AlipayBillRecordVO> getAlipayBillRecord()
  {
    MapSqlParameterSource paramMap = new MapSqlParameterSource();
    Calendar importTime = Calendar.getInstance();
    importTime.add(5, -1);
    paramMap.addValue("importTime", importTime.getTime());
    return queryForList("select  tran_no,merchant_order,trade_create_time,pay_time,recent_update_time,trade_origin,type,trade_opposite,goods_name,amount,income_expenditure,trade_state,service_charge,refund_amount,remark,ischeck,import_time  from alipay_bill_record where 1=1   and import_time>=:importTime  order by trade_create_time desc ", paramMap, AlipayBillRecordVO.class);
  }
  
  public AlipayBillRecordVO getAliPayBillRecordByTranNo(final String tranNo)
  {
    try
    {
    	 MapSqlParameterSource paramMap = new MapSqlParameterSource();
      	  paramMap.addValue("tranNo", tranNo);
      	return  (AlipayBillRecordVO)this.jdbcTemplate.queryForObject("select  tran_no,merchant_order,trade_create_time,pay_time,recent_update_time,trade_origin,type,trade_opposite,goods_name,amount,income_expenditure,trade_state,service_charge,refund_amount,remark,ischeck,import_time  from alipay_bill_record where 1=1   and tran_no=:tranNo ", paramMap, new BeanPropertyRowMapper(AlipayBillRecordVO.class));
    }
    catch (DataAccessException e)
    {
      LogUtil.debug("查询支付宝账户对象为空,交易号:" + tranNo);
    }
    return null;
  }
  
  public int[] insertAlipayBillRecord(List<AlipayBillRecordVO> alipayBillRecordList)
    throws Exception
  {
    return batchSave("insert into alipay_bill_record(tran_no,merchant_order,trade_create_time,pay_time,recent_update_time,trade_origin,type,trade_opposite,goods_name,amount,income_expenditure,trade_state,service_charge,refund_amount,remark,ischeck,import_time)  values(:tranNo,:merchantOrder,:tradeCreateTime,:payTime,:recentUpdateTime,:tradeOrigin,:type,:tradeOpposite,:goodsName,:amount,:incomeExpenditure,:tradeState,:serviceCharge,:refundAmount,:remark,:ischeck,CURRENT_TIMESTAMP ) ", alipayBillRecordList);
  }
  
  protected List<ChannelCheckdetailVO> getChannelCheckDetailList()
    throws Exception
  {
    LogUtil.info("支付宝渠道对账，会计账务日期：" + DateUtil.getStringByYMD(this.accountingDate));
    List<ChannelCheckdetailVO> result = new ArrayList();
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("channelCode", getChannelNo());
    
    List<Map<String, Object>> checkDetailList = findListBySql("SELECT a.channel_code,a.accounting_date as tran_accounting_date,a.trade_no,a.plat_time,a.payment_amount,  a.pay_state_code,a.pay_type_code,b.amount as thd_amount,b.refund_amount,b.trade_state,b.tran_no as thd_tran_no from ms_tran_info a LEFT JOIN  alipay_bill_record b on    a.order_no=b.merchant_order  where a.channel_code=:channelCode and  (a.check_account_sate is null or a.check_account_sate='00')   ", parameters);
    ChannelCheckdetailVO channelCheckdetailVo = null;
    List<Map<String, String>> aliparamList = new ArrayList();
    List<Map<String, String>> traninfoparamList = new ArrayList();
    String channelCode = null;
    String tradeNo = null;
    Date tranAccountingDate = null;
    Date platTime = null;
    BigDecimal paymentAmount = null;
    Integer payStateCode = null;
    Integer payTypeCode = null;
    BigDecimal thdAmount = null;
    BigDecimal refundAmount = null;
    String tradeState = null;
    String thdTranNo = null;
    for (Map<String, Object> checkDetail : checkDetailList)
    {
      channelCode = (String)checkDetail.get("channelCode");
      tradeNo = (String)checkDetail.get("tradeNo");
      tranAccountingDate = (Date)checkDetail.get("accountingDate");
      platTime = (Date)checkDetail.get("platTime");
      paymentAmount = (BigDecimal)checkDetail.get("paymentAmount");
      payStateCode = (Integer)checkDetail.get("payStateCode");
      payTypeCode = (Integer)checkDetail.get("payTypeCode");
      thdAmount = (BigDecimal)checkDetail.get("thdAmount");
      refundAmount = (BigDecimal)checkDetail.get("refund_amount");
      tradeState = (String)checkDetail.get("tradeState");
      tradeState = tradeState != null ? tradeState : "";
      thdTranNo = (String)checkDetail.get("thdTranNo");
      if (paymentAmount != null)
      {
        thdAmount = thdAmount != null ? thdAmount : BigDecimal.ZERO;
        if (paymentAmount.compareTo(thdAmount) != 0)
        {
          if ((refundAmount != null) && (refundAmount.compareTo(BigDecimal.ZERO) > 0)) {}
          channelCheckdetailVo = new ChannelCheckdetailVO();
          channelCheckdetailVo.setChannelCode(channelCode);
          channelCheckdetailVo.setAccountingCode(this.accountingDate);
          channelCheckdetailVo.setTradeNo(tradeNo);
          channelCheckdetailVo.setTranDate(tranAccountingDate);
          channelCheckdetailVo.setTranAmount(paymentAmount);
          channelCheckdetailVo.setPlatPayTime(platTime);
          channelCheckdetailVo.setPlatPayState(payStateCode);
          channelCheckdetailVo.setPlatPayType(payTypeCode);
          String chnlState = "交易成功".equals(tradeState) ? "1" : "0";
          channelCheckdetailVo.setChnlState(chnlState);
          channelCheckdetailVo.setCheckState(Integer.valueOf(1));
          channelCheckdetailVo.setCheckResult(Integer.valueOf(5));
          channelCheckdetailVo.setMannulFlag(Integer.valueOf(0));
          result.add(channelCheckdetailVo);
        }
      }
      if ((thdTranNo != null) && (!"".equals(thdTranNo)))
      {
        Map<String, String> param = new HashMap();
        param.put("tranNo", thdTranNo);
        aliparamList.add(param);
      }
      Map<String, String> param = new HashMap();
      param.put("tradeNo", tradeNo);
      param.put("checkAccountSate", "02");
      traninfoparamList.add(param);
    }
    batchupdateBySql("update alipay_bill_record set isCheck=1 where  tran_no=:tranNo ", (Map[])aliparamList.toArray(new Map[0]));
    batchupdateBySql("update ms_tran_info set check_account_sate=:checkAccountSate where trade_no=:tradeNo ", (Map[])traninfoparamList.toArray(new Map[0]));
    return result;
  }
  
  protected String getChannelNo()
  {
    return CHANNEL_NO;
  }
}
